<?php
	class RelationshipController extends CustomControllerAction 
	{
		protected $_flash;

		public function init() 
		{
			parent::init();
			$this->_flash = $this->_helper->getHelper('FlashMessenger');
			$this->_redirector = $this->_helper->getHelper('Redirector');
		}
	
		public function indexAction() { }
		
		public function followAction()
		{
			$request = $this->getRequest();

			# get user id from request
			if ($request->isPost())
			{
				# get user id to follow
				$user_to_follow_id = $request->getPost('user_id');

				# get user requesting to follow that id
				$auth = Zend_Auth::getInstance();
				$identity = $auth->getIdentity();
				$user_requesting_id = $identity->id;
				
				if (isset($user_requesting_id) && isset($user_to_follow_id))
				{
					# determine if following already exists
					$following_mgr = new FollowingSDBManager();
					$followings = $following_mgr->query("['user_id' = '$user_requesting_id'] intersection ['following_id' = '$user_to_follow_id']");

					# check if relationship already exists
					$relationship_mgr = new RelationshipSDBManager();
					$relationships = $relationship_mgr->query("['user_id_a' = '$user_requesting_id' or 'user_id_a' = '$user_to_follow_id'] "
						. "intersection ['user_id_b' = '$user_to_follow_id' or 'user_id_b' = '$user_requesting_id']");
					
					if (sizeof($relationships) == 0 && sizeof($followings) == 0 && ($user_requesting_id != $user_to_follow_id))
					{
						# check if requested user is following requesting user
						$followings = $following_mgr->query("['user_id' = '$user_to_follow_id'] intersection ['following_id' = '$user_requesting_id']");
						
						if (sizeof($followings) == 0)
						{
							# create following
							$attributes = array(
								'user_id' => $user_requesting_id,
								'following_id' => $user_to_follow_id
							);
							
							$following = new Following();
							$following->setAttributes($attributes);
							$following->save();
						}
						else
						{
							# create friendship
							$attributes = array(
								'user_id_a' => $user_requesting_id,
								'user_id_b' => $user_to_follow_id
							);

							$relationship = new Relationship();
							$relationship->setAttributes($attributes);
							$relationship->save();
							$followings[0]->delete();
						}
					}
					else
					{
						# flash relationship or following already exists
						die ('relationship or following already exists');
					}
				}
				else
				{
					# flash not logged in, bitch
					die ('not logged in, asshole.');
				}
			}
		}
		
		public function unfollowAction()
		{
			$request = $this->getRequest();

			# get user id from request
			if ($request->isPost())
			{
				# get user id to follow
				$user_to_follow_id = $request->getPost('user_id');

				# get user requesting to follow that id
				$auth = Zend_Auth::getInstance();
				$identity = $auth->getIdentity();
				$user_requesting_id = $identity->id;
				
				if (isset($user_requesting_id) && isset($user_to_follow_id))
				{
					# determine if following already exists
					$following_mgr = new FollowingSDBManager();
					$followings = $following_mgr->query("['user_id' = '$user_requesting_id'] intersection ['following_id' = '$user_to_follow_id']");
					
					if (sizeof($followings) > 0)
						$followings[0]->delete();
					else
						die ('no following to delete, asshole.');

				}
				else
				{
					# flash not logged in, bitch
					die ('not logged in, asshole.');
				}
			}
		}
		
		public function denyfollowingAction()
		{
			$request = $this->getRequest();

			# get user id from request
			if ($request->isPost())
			{
				# get user id to follow
				$user_to_follow_id = $request->getPost('user_id');

				# get user requesting to follow that id
				$auth = Zend_Auth::getInstance();
				$identity = $auth->getIdentity();
				$user_requesting_id = $identity->id;
				
				if (isset($user_requesting_id) && isset($user_to_follow_id))
				{
					# determine if following already exists
					$following_mgr = new FollowingSDBManager();
					$followings = $following_mgr->query("['user_id' = '$user_to_follow_id'] intersection ['following_id' = '$user_requesting_id']");
					
					if (sizeof($followings) > 0)
						$followings[0]->delete();
					else
						die ('no following to deny, asshole.');
				}
				else
				{
					# flash not logged in, bitch
					die ('not logged in, asshole.');
				}
			}
		}

		public function followingsAction() {

			# Get logged in user's id
			$auth = Zend_Auth::getInstance();
			$identity = $auth->getIdentity();
			$user_id= $identity->id;

			if ($user_id) {

			# Set $view so we can figure out if we're to display everything on this page 
			# or just one # particular piece.
			$view = $this->getRequest()->getParam('view');

			# Grab what page we're on for use in pagination
			$page = $this->getRequest()->getParam('p');

			# This is the number of media pieces to show on this page from friends and
			#	people this user is following. $start is the record number to start with (used in pagination)
			if (!$view) {
				$limit = 10;
			}
			else {
				$limit = 1;
			}

			if (($page) && is_numeric($page))  {
				$start = (($page - 1) * $limit);
			}
			else {
				$start = 0;
				$page = 1;
			}

			# print "start: $start, limit: $limit<br />";

			# This is the limit on new comments the user will see on his/her photos and 
			#	replies to his/her comments.
			$new_comment_limit = 30;

			# Create media, user, and comment objects for use below
			$media = new MediaSDBManager();
			$user = new User();
			$comment_obj = new CommentSDBManager();


			if (($view == 'allfriends') || !$view) {

			## Get new media from the user's friends 
			$followings = new RelationshipSDBManager();
			$followings_result = $followings->getByFieldValue('user_id_b', $user_id);

			foreach($followings_result as $following) {
				
				# Get the id of this friend 
				$friend_id = $following->getAttribute('user_id_a');

				# Get friend's media
				$media_results = $media->getByFieldValue('user_id', $friend_id);

				foreach($media_results as $media_piece) {
	
					# Get attributes for this piece of media
					$friends_media[$media_piece->getAttribute('date')] = $media_piece->getAttributes();
					
					# Get user's username
					$user->load($friend_id);
					$friends_media[$media_piece->getAttribute('date')]['username'] = $user->getAttribute('username');

					# Get thumbnail
					$desired_thumb_width = "160";
					$thumb_mgr = new ThumbnailManager($this->_sdb, $this->_s3, $this->_config, $this->_logger);
					$friends_media[$media_piece->getAttribute('date')]['thumb_url'] = 
																							$thumb_mgr->getThumbnail($media_piece->getId(), $desired_thumb_width);
				}
			}
		
			if (count($friends_media)) {

				# Limit number of friends_medias
				$friends_media_total = count($friends_media);
				$friends_media = array_splice($friends_media, $start, $limit);

				# Sort by date and send to the template
				krsort($friends_media);
				$this->view->friends_media = $friends_media;
				$this->view->friends_media_total = $friends_media_total;
			}
			}

			if (($view == 'allfollowing') || !$view) {

			## Get list of other users this user is following
			$followings = new FollowingSDBManager();
			$followings_result = $followings->getByFieldValue('user_id', $user_id);

			foreach($followings_result as $following) {
				
				# Get the id of the user being followed 
				$followed_id = $following->getAttribute('following_id');

				# Get followed user's media
				$media_results = $media->getByFieldValue('user_id', $followed_id);
				
				foreach($media_results as $media_piece) {
	
					# Get attributes for this piece of media
					$followed_media[$media_piece->getAttribute('date')] = $media_piece->getAttributes();

					# Get user's username
					$user->load($followed_id);
					$followed_media[$media_piece->getAttribute('date')]['username'] = $user->getAttribute('username');

					# Get thumbnail
					$desired_thumb_width = "160";
					$thumb_mgr = new ThumbnailManager($this->_sdb, $this->_s3, $this->_config, $this->_logger);
					$followed_media[$media_piece->getAttribute('date')]['thumb_url'] = 
																							$thumb_mgr->getThumbnail($media_piece->getId(), $desired_thumb_width);
				}
			}

			if (count($followed_media)) {

				# Limit the number of followed_medias
				$followed_media_total = count($followed_media);
				$followed_media = array_splice($followed_media, $start, $limit);

				# Sort by date and send to the template
				krsort($followed_media);
				$this->view->followed_media = $followed_media;
				$this->view->followed_media_total = $followed_media_total;
			}
			}
			
			if (($view == 'photocomments') || !$view) {

			## Get comments on photos the logged in user submitted
			$media_results = $media->getByFieldValue('user_id', $user_id);

			foreach($media_results as $my_media_piece) {

				$media_id = $my_media_piece->getId();

				# Find comments made by other users on media items that the logged in user submitted
				$comment_obj_result = $comment_obj->query("['photo_id' = '$media_id'] intersection ['user_id' != '$user_id'] intersection ['date' > '0'] sort 'date' desc");
				
				foreach($comment_obj_result as $comment) {
					
					$comment_attributes = $comment->getAttributes();

					# Get commenter's username
					$user->load($comment_attributes['user_id']);
					$comment_attributes['username'] = $user->getAttribute('username');

					$photo_id = $comment_attributes['photo_id'];

					$new_comments[$photo_id]['photo_url'] = $my_media_piece->getAttribute('url');
					$new_comments[$photo_id]['photo_title'] = $my_media_piece->getaTtribute('title');
					$new_comments[$photo_id]['comments'][] = $comment_attributes; // $comment->getAttributes();
				}
			}

			if (count($new_comments)) {
			
				# Limit the number of followed_medias
				$new_comments = array_splice($new_comments, 0, $new_comment_limit);

				# Sort by date and send to the template
				krsort($new_comments);
				$this->view->new_comments = $new_comments;
			}
			}

			if (($view == 'replycomments') || !$view) {

			## Get responses to comments the logged in use has made
			$comment_obj_result2 = $comment_obj->query("['user_id' = '$user_id'] intersection ['date' > '0'] sort 'date' desc");

			foreach($comment_obj_result2 as $user_comment) {

				$user_comment_array = $user_comment->getAttributes();

				if (!isSet($last_comments[$user_comment_array['photo_id']])) { 
					$last_comments[$user_comment_array['photo_id']] = $user_comment_array;
				}
			}

			# Figure out the last comment the user made on every photo they've commented on
			foreach($last_comments as $photo_id => $comment_details) {
				
				$timestamp = $comment_details['date'];
				
				# Figure out if there were any comments made after the user's last comment on every photo they've commented on
				$any_later_comments = $comment_obj->query("['photo_id' = '$photo_id'] intersection ['date' > '$timestamp'] sort 'date' asc");

				if (count($any_later_comments)) {
					
					# Get photo's title
					$media = new Media();
					$media->load($photo_id);

					$reply_comments[$photo_id]['title'] = $media->getAttribute('title');
					$reply_comments[$photo_id]['url'] = $media->getAttribute('url');

					# Set original comment data
					$reply_comments[$photo_id]['original_comment'] = array(
						'comment' => $comment_details['comment'],
						'date' => $comment_details['date']
					);

					foreach($any_later_comments as $later_comment) {
						$later_comment_array = $later_comment->getAttributes();
						
						# Get commenter's username
						$user->load($later_comment_array['user_id']);
						
						$reply_comments[$later_comment_array['photo_id']]['comments'][] = array(
							'comment' => $later_comment_array['comment'],
							'username' => $user->getAttribute('username'),
							'date' => $later_comment_array['date']
						);
					}
				}
			}

			if (count($reply_comments)) {
				
				# Send reply comments to the view
				$this->view->reply_comments = $reply_comments;
			}
			}

			# Let the template know what the $view option was set to,
			# as well as what the $limit value is
			$this->view->view = $view;
			$this->view->limit = $limit;
			$this->view->page = $page;

			}
			else {
				
				# Redirect to the login page
				$this->_flash->addMessage("You must be logged in to do this.");
				$this->_redirector->gotoUrl('/account/login');
			}
		}
	}
